package com.niiwoo.civet.account.service.local.check.job.check;

import java.util.ArrayList;
import java.util.List;

import com.niiwoo.civet.account.service.local.check.job.api.ParseService;
import com.niiwoo.civet.account.service.local.check.job.properties.AccountCheckingProperties;

public class NumDispatcher<T> {
	private AccountCheckingProperties properties;
	
	private ParseService<T> parseService;
	
	private List<T> list;
	public NumDispatcher(AccountCheckingProperties properties, ParseService<T> parseService) {
		this.properties = properties;
		this.parseService = parseService;
		list = new ArrayList<T>();
	}
	
	private int total = 0;
	
	public void receive(T t) {
		//当容量达到上限则启动一个线程调用对应的服务或者直接调用服务bean对应的处理方法
		boolean maxCapacity = false;
		List<T> tmp = null;
		synchronized (this) {
			total++;
			if (list.size() >= properties.getBatch2dbCapacity()) {
				tmp = list;
				list = new ArrayList<T>();
				
				list.add(t);
				
				maxCapacity = true;
			}
		}
		
		if (maxCapacity) {
			parseService.save(tmp);
			tmp = null;
		} else {
			list.add(t);
		}
	}

	public void notifyDone() {
		if (list != null && !list.isEmpty()) {
			parseService.save(list);
		}
	}
}
